<template>
    <a-menu
        theme="dark"
        mode="inline"
        @openChange="onOpenChange"
        :openKeys="state.openKeys"
        @select="onSelect"
        :selectedKeys="selectedKeys"
    >
        <template v-for="item in treeData" :key="item.key">
            <template v-if="!item.children">
                <a-menu-item :key="item.key">
                    <component :is="$Icon[item.icon]" />
                    <span>{{ item.title }}</span>
                </a-menu-item>
            </template>
            <template v-else>
                <NavSubMenu :datas="item" :key="item.key" />
            </template>
        </template>
    </a-menu>
</template>

<script lang="ts" setup>
import { reactive, ref, defineProps, withDefaults, defineEmits } from 'vue'
import { NavMenuJson, TreeHelper } from '@/core/NavMenuTreeHelper';
import { SysMenu } from '@/models/System/SysMenu';
import NavSubMenu from '@/components/NavMenu/NavSubMenu.vue';

/**
 * 属性参数
 */
interface IProps {
    /**
     * 菜单数据
     */
    datas: SysMenu.Base[],

    /**
     * 默认打开
     */
    opend?: []
}

const props = withDefaults(defineProps<IProps>(), {
    opend: () => []
});


const emits = defineEmits(["onSelect"]);


let tree = TreeHelper.getNavMenuTree(props.datas, 0);
let rootKey = TreeHelper.getNavMenuRootKey(tree);

const treeData = ref<NavMenuJson[]>(tree);

const state = reactive<
    {
        rootSubmenuKeys: number[]
        openKeys: number[]
    }
>({
    rootSubmenuKeys: rootKey,
    openKeys: []
});

const selectedKeys = ref<number[]>([]);


const onOpenChange = (openKeys: any) => {
    state.openKeys = openKeys;
    // const latestOpenKey = openKeys.find(key => state.openKeys.indexOf(key) == -1);
    // if (state.rootSubmenuKeys.indexOf(latestOpenKey) == -1) {
    //     state.openKeys = openKeys;
    //     console.log(">-1", openKeys);
    // } else {
    //     console.log(">-1", latestOpenKey);
    //     state.openKeys = latestOpenKey ? [latestOpenKey] : [];
    // }
};



const onSelect = (item: any) => {
    let data = props.datas.find(f => f.id == item.key);
    emits("onSelect", data);

    selectedKeys.value = item.selectedKeys;
    localStorage.setItem("_NavMenuKeyPath", JSON.stringify(item.keyPath));
    localStorage.setItem("_NavMenuSelectedKeys", JSON.stringify(item.selectedKeys));

    console.log("菜单选中");
}

const InitOpenKeys = () => {
    let keyPath = localStorage.getItem("_NavMenuKeyPath");
    let keys: any = localStorage.getItem("_NavMenuSelectedKeys");
    if (keyPath !== undefined && keyPath != "" && keyPath != null) {
        state.openKeys = JSON.parse(keyPath);
        selectedKeys.value = JSON.parse(keys);
    }
}

InitOpenKeys();

</script>